package com.iptv.grape.load_apk;

import java.io.IOException;

import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

/****
 * 下载进度
 */
public class LoadResponseBody extends ResponseBody{

    private Response originalResponse;
    private LoadListener downloadListener;
    private long oldPoint = 0;

    public LoadResponseBody(Response originalResponse, long startsPoint, LoadListener downloadListener){
        this.originalResponse = originalResponse;
        this.downloadListener = downloadListener;
        this.oldPoint = startsPoint;
    }

    @Override
    public MediaType contentType() {
        return originalResponse.body().contentType();
    }

    @Override
    public long contentLength() {
        return originalResponse.body().contentLength();
    }

    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
            private long bytesReaded = 0;
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                bytesReaded += bytesRead == -1 ? 0 : bytesRead;
                if (downloadListener != null) {
                    downloadListener.loading((int) ((bytesReaded+oldPoint)/(1024)));
                }
                return bytesRead;
            }
        });
    }

}

